﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace hextrans
{
    class Class1line
    {
        private Byte length=0;
       
        private Byte[] addr=new Byte[2];
        private Byte type=0;
        private Byte[] buffer = new Byte[16];
        private Byte check=0;
        private Byte all = 0;
       

        public Class1line() {; }
        public void Reload(string str)
        {
            UInt16 Ulength = 0;
            this.length = Convert.ToByte(str.Substring(1, 2), 16);
            this.all = 0;
            Ulength = Convert.ToUInt16(length);
            if (Ulength == 0) return;
            this.all += this.length;
             this.addr[1] = Convert.ToByte(str.Substring(3, 2), 16);
             this.all += this.addr[1];
               this.addr[0] = Convert.ToByte(str.Substring(5, 2), 16);
               this.all += this.addr[0];
               this.type = Convert.ToByte(str.Substring(7, 2), 16);
               this.all += this.type;
            for (int i = 0; i < Ulength; i ++)
            {
               this.buffer[i] = Convert.ToByte(str.Substring((i*2+9), 2), 16);
               this.all += this.buffer[i];
            }
             this.check = Convert.ToByte(str.Substring((Ulength * 2 + 9), 2), 16);
                
            
           // throw new System.NotImplementedException();

        }

        public String Offset(Byte offset)
        {
            string str1=":";
            UInt16 Ulength = 0;
            Ulength = Convert.ToUInt16(length);
            //if (offset==0x10) return("3234");

            this.all += offset;
            this.check = (Byte)(256 - this.all);

            str1 += hextostring(this.length);
            this.addr[1] += offset;
            str1 += hextostring(this.addr[1]);

            str1 += hextostring(this.addr[0]);

            str1 += hextostring(this.type);
              
            for (int i = 0; i < Ulength; i++)
            {
                str1 += hextostring(this.buffer[i]);
            }
            str1 += hextostring(this.check); 
            return (str1.ToUpper());
            //throw new System.NotImplementedException();
        }

        private string hextostring(Byte val)
        {
            if (val > 0x0f) return (Convert.ToString(val, 16));
            if (val < 0x10) return ("0"+Convert.ToString(val, 16));
            if (val ==0){return ("00");}
            throw new System.NotImplementedException();
        }
    }
}
